import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutterlib/common/net/api_file.dart';
import 'package:flutterlib/common/style/quhui_style.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/common/utils/version_utils.dart';
import 'package:flutterlib/model/app_version.dart';
import 'package:flutterlib/pages/activity/list/page.dart' as activityList;
import 'package:flutterlib/pages/interest/list/page.dart' as interestList;
import 'package:flutterlib/pages/interest/viewmodel/interest_store.dart';
import 'package:flutterlib/pages/post/list/page.dart' as postList;
import 'package:flutterlib/pages/user/mine/page.dart' as userMine;
import 'package:flutterlib/widgets/app_flowable_view.dart';
import 'package:flutterlib/widgets/bottom_bar_view.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:flutterlib/widgets/update/flutter_update_dialog.dart';
import 'package:mobx/mobx.dart';
import 'package:package_info/package_info.dart';
import 'package:thrio/thrio.dart';

/**
 * 主页
 * Created by guoshuyu
 * Date: 2018-07-16
 */
class Page extends StatefulWidget {
  static final String sName = "home";

  @override
  _PageState createState() => _PageState();
}

class _PageState extends State<Page> with AutomaticKeepAliveClientMixin {
  List<TabIconData> tabIconsList = TabIconData.tabIconsList;
  UpdateDialog dialog;
  AppVersion _lastAppVersion;
  final SettingsStore store =
      Provider.of<SettingsStore>(currentContext, listen: false);
  InterestStore interestStore = InterestStore();
  DateTime _lastPressedAt; //上次点击时间
  final CancelToken _cancelToken = CancelToken();
  final PageController _controller = PageController(
    initialPage: 0,
    keepPage: true,
  );
  PageStorageKey pageStorageKey = new PageStorageKey("pageview");
  static OverlayEntry entry;
  @override
  void initState() {
    super.initState();
    trueDebugPrint("flutterting _HomePageState init");

    //初始化settingstore中的全局用户状态
    loginUserLast();

    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      String appName = packageInfo.appName;
      String packageName = packageInfo.packageName;
      String version = packageInfo.version;
      String buildNumber = packageInfo.buildNumber;
      trueDebugPrint("flutterting" + version + '' + appVersion.lastVersion);
      _lastAppVersion = appVersion;
      if (version < _lastAppVersion.lastVersion) {
        customStyle();
      }
    });

    SchedulerBinding.instance.addPostFrameCallback((_) {
      entry?.remove();
      entry = null;
      entry = OverlayEntry(builder: (context) {
        return AppFloatBox();
      });
      Overlay.of(context).insert(entry);
    });
  }

  void loginUserLast() {
    store.setUserEntity(userFromStore);
  }

  /// 不退出
  Future<bool> dialogExitApp() async {
    final bool confirm = await ConfirmationDialog.show(
      context,
      title: '退出',
      content: '是否退出应用？',
      showConfirm: true,
    );
    if (confirm) {
      NavigatorUtils.ThrioNavigatorPop();
      return true;
    }
    return false;
  }

  _renderTab(icon, text) {
    return new Tab(
      child: new Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[new Icon(icon, size: 16.0), new Text(text)],
      ),
    );
  }

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(covariant Page oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    ///增加返回按键监听
    ScreenUtil.init(context,
        designSize: Size(375, 667), allowFontScaling: false);
    trueDebugPrint(
        "flutterting" + "homepage do builder" + _controller.toString());
    return Scaffold(
      backgroundColor: QuhuiColors.white,
      bottomNavigationBar: SizedBox(
        height: 62,
        child: bottomBar(),
      ),
      body: Observer(
        builder: (_) {
          var userEntity = store.userEntity;
          trueDebugPrint(
              "fluttermobx userentity" + ((userEntity?.uid) ?? 0).toString());
          return PageView(
            controller: _controller,
            children: <Widget>[
              Observer(
                builder: (_) {
                  var userEntity = store.userEntity;
                  trueDebugPrint("fluttermobx userentity" +
                      ((userEntity?.uid) ?? 0).toString());
                  return postList.Page(
                    key: ObjectKey(userEntity),
                  );
                },
              ),
              interestList.Page(),
              Observer(builder: (_) {
                var interests = store.interests;
                return activityList.Page(
                    key: ValueKey(interests.length), interests: interests);
              }),
              userMine.Page(),
            ],
            physics: NeverScrollableScrollPhysics(),
          );
        },
      ),
    );
  }

  Widget tabBody = Container(
    color: QuhuiColors.white,
  );

  Widget bottomBar() {
    return Column(
      children: <Widget>[
        BottomBarView(
          beforeChange: (int index) {
            if (currentUser == null && [1, 2].contains(index)) {
              NavigatorUtils.goLogin(context);
              return false;
            }
            return true;
          },
          tabIconsList: tabIconsList,
          addClick: () {
            if (!isLogin) {
              NavigatorUtils.goLogin(context);
              return;
            }
            if (store.interests.length == 0) {
              NavigatorUtils.gotoAddInterestPage(context);
            } else {
              NavigatorUtils.gotoActionSelectPage(context);
            }
          },
          changeIndex: (int index) {
            _controller.jumpToPage(index);
            // setState(() {
            //   mainState.setTabBarSelectedIndex = index;
            // });
          },
        ),
      ],
    );
  }

  ///下载apk
  Future<void> _download() async {
    try {
      ToastUtils.success("开始升级...");
      setInitDir(initStorageDir: true);
      await DirectoryUtil.getInstance();
      DirectoryUtil.createStorageDirSync(category: 'Download');
      final String path = DirectoryUtil.getStoragePath(
          fileName: 'quhui', category: 'Download', format: 'apk');
      final File file = File(path);
      await HttpManagerFile().getDio().download(
        appVersion.url,
        file.path,
        cancelToken: _cancelToken,
        onReceiveProgress: (int count, int total) {
          if (total != -1) {
            dialog.update(count / total);
            if (count == total) {
              dialog.dismiss();
              ToastUtils.success("升级成功！");
              VersionUtils.install(path);
            }
          }
        },
      );
    } catch (e) {
      ToastUtils.error("升级失败！");
      print(e);
    }
  }

  void customStyle() {
    if (dialog != null && dialog.isShowing()) {
      return;
    }
    dialog = UpdateDialog.showUpdate(context,
        width: 250,
        title: "是否升级到${_lastAppVersion.lastVersion}版本？",
        updateContent: _lastAppVersion.info,
        titleTextSize: 14,
        contentTextSize: 12,
        buttonTextSize: 12,
        topImage: Image.asset('assets/images/bg_update_top.png'),
        extraHeight: 5,
        radius: 8,
        themeColor: Color(0xFFFFAC5D),
        progressBackgroundColor: Color(0x5AFFAC5D),
        isForce: true,
        updateButtonText: '升级',
        ignoreButtonText: '忽略此版本',
        enableIgnore: _lastAppVersion.forceUpdate ? false : true, onIgnore: () {
      trueDebugPrint("no update app");
      // ToastUtils.waring("忽略");
      dialog.dismiss();
    }, onUpdate: _download);
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
